package org.jks.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jks.config.Config;
import org.jks.model.Department;
import org.jks.model.Device;
import org.jks.model.DeviceRecipient;
import org.jks.model.Flight;
import org.jks.model.RecipientOrder;
import org.jks.model.User;
import org.jks.report.model.ReportDeviceRecipientModel;
import org.jks.request.model.Ids;
import org.jks.request.model.UIDeviceRecipient;
import org.jks.request.model.UIRecipientOrder;
import org.jks.response.model.ActionResult;
import org.jks.response.model.UITable;
import org.jks.service.DeviceRecipientService;
import org.jks.service.DeviceService;
import org.jks.util.DateUtil;
import org.jks.util.ExportUtil;
import org.jks.util.JsonUtil;
import org.jks.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/device_recipient")
public class DeviceRecipientController {
	@Autowired
	DeviceRecipientService deviceRecipientService;
	@Autowired
	DeviceService deviceService;

	@RequestMapping("/add")
	public void add(HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		ActionResult ar = new ActionResult();
		String json = "";
		String OrderNo = "DR_"
				+ DateUtil.toString(new Date(), "yyyyMMddHHmmss");
		try {
			json = JsonUtil.getJson(request.getReader());
			UIDeviceRecipient uiDeviceRecipient = (UIDeviceRecipient) JsonUtil
					.Json2Object(json, UIDeviceRecipient.class);
			DeviceRecipient deviceRecipient = new DeviceRecipient();
			Department department = new Department();
			department.setId(uiDeviceRecipient.getDepartmentId());
			deviceRecipient.setDepartment(department);
			Flight group = new Flight();
			group.setId(uiDeviceRecipient.getGroupId());
			deviceRecipient.setGroup(group);
			deviceRecipient.setTime(DateUtil.toDate(
					uiDeviceRecipient.getTime(), "yyyy-MM-dd HH:mm:ss"));
			User user = new User();
			user.setId(uiDeviceRecipient.getUserId());
			deviceRecipient.setRecipients(user);
			deviceRecipient.setDesp(uiDeviceRecipient.getDesp());
			deviceRecipient.setOrderNo(OrderNo);

			List<RecipientOrder> recipientOrders = new ArrayList<RecipientOrder>();
			boolean err = false;
			for (UIRecipientOrder uiRecipientOrder : uiDeviceRecipient
					.getOrders()) {
				RecipientOrder recipientOrder = new RecipientOrder();
				Device device = new Device();
				device.setId(uiRecipientOrder.getDeviceId());
				device = deviceService.findById(device.getId());
				recipientOrder.setDevice(device);
				long count = deviceService.countByType(device.getType());
				if(uiRecipientOrder.getCount() > count){
					err = true;
					break;
				}
				recipientOrder.setCount(uiRecipientOrder.getCount());
				recipientOrder.setDeviceRecipient(deviceRecipient);
				recipientOrders.add(recipientOrder);
			}
			if(!err){
				deviceRecipient.setRecipientOrders(recipientOrders);
				deviceRecipientService.save(deviceRecipient);
				ar.setSuccess(true);
			}
			else{
				ar.setMsg("操作失败，设备申请数大于可用设备数！");
			}
		} catch (IOException e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}

	public void add(DeviceRecipient deviceRecipient,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			deviceRecipientService.save(deviceRecipient);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/delete/{id}")
	public void delete(@PathVariable long id, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			deviceRecipientService.delete(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/delete")
	public void delete(Ids ids, HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		ActionResult ar = new ActionResult();
		try {
			for (long id : ids.getIds()) {
				deviceRecipientService.delete(id);
			}
			ar.setSuccess(true);
		} catch (Exception e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}

	@RequestMapping("/detail/{id}")
	public ModelAndView detail(@PathVariable long id,
			HttpServletRequest request, HttpSession session,
			HttpServletResponse response, Map<String, Object> model) {
		try {
			DeviceRecipient deviceRecipient = deviceRecipientService
					.findById(id);
			if (deviceRecipient != null) {
				deviceRecipient.getRecipientOrders().size();
				for (RecipientOrder recipientOrder : deviceRecipient
						.getRecipientOrders()) {
					recipientOrder.setDeviceRecipient(null);
				}
			}
			model.put("deviceRecipient", JsonUtil.Object2Json(deviceRecipient));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Config.init(request, response, session, model);
		return new ModelAndView("wuziMgr/wz_recipient_detail", model);
	}

	@RequestMapping("/update")
	public void update(HttpServletRequest request, HttpServletResponse response) {
		ActionResult ar = new ActionResult();
		String json = "";
		try {
			json = JsonUtil.getJson(request.getReader());
			UIDeviceRecipient uiDeviceRecipient = (UIDeviceRecipient) JsonUtil
					.Json2Object(json, UIDeviceRecipient.class);
			DeviceRecipient deviceRecipient = deviceRecipientService
					.findById(uiDeviceRecipient.getId());
			;
			Department department = new Department();
			department.setId(uiDeviceRecipient.getDepartmentId());
			deviceRecipient.setDepartment(department);
			Flight group = new Flight();
			group.setId(uiDeviceRecipient.getGroupId());
			deviceRecipient.setGroup(group);
			deviceRecipient.setTime(DateUtil.toDate(
					uiDeviceRecipient.getTime(), "yyyy-MM-dd HH:mm:ss"));
			User user = new User();
			user.setId(uiDeviceRecipient.getUserId());
			deviceRecipient.setRecipients(user);
			deviceRecipient.setDesp(uiDeviceRecipient.getDesp());
			deviceRecipient.getRecipientOrders().clear();
			deviceRecipientService.update(deviceRecipient);

			List<RecipientOrder> recipientOrders = new ArrayList<RecipientOrder>();
			for (UIRecipientOrder uiRecipientOrder : uiDeviceRecipient
					.getOrders()) {
				RecipientOrder recipientOrder = new RecipientOrder();
				Device device = new Device();
				device.setId(uiRecipientOrder.getDeviceId());
				recipientOrder.setDevice(device);
				recipientOrder.setCount(uiRecipientOrder.getCount());
				recipientOrder.setDeviceRecipient(deviceRecipient);
				recipientOrders.add(recipientOrder);
			}
			deviceRecipient.setRecipientOrders(recipientOrders);
			deviceRecipientService.update(deviceRecipient);
			ar.setSuccess(true);
		} catch (IOException e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}

	public void update(DeviceRecipient deviceRecipient,
			HttpServletRequest request, HttpServletResponse response) {
		ActionResult ar = new ActionResult();
		try {
			deviceRecipientService.update(deviceRecipient);
			ar.setSuccess(true);
			ar.setData(deviceRecipient);
		} catch (Exception e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}

	@RequestMapping("/all")
	public void all(HttpServletRequest request, HttpServletResponse response) {
		ActionResult ar = new ActionResult();
		String[] limit = request.getParameterValues("limit");
		String[] pages = request.getParameterValues("page");
		int pagesize = 25;
		int page = 1;
		if(limit.length > 0){
			pagesize = Integer.valueOf(limit[0]);
		}
		if(pages.length > 0){
			page = Integer.valueOf(pages[0]);
		}
		try {
			long total = deviceRecipientService.count();
			List<DeviceRecipient> deviceRecipients = deviceRecipientService
					.list(page, pagesize);
			for (DeviceRecipient deviceRecipient : deviceRecipients) {
				deviceRecipient.setRecipientOrders(null);
			}
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setTotal(total);
			table.setRows(deviceRecipients);
			ar.setData(table);
		} catch (Exception e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/export/{id}")
	public void export(@PathVariable long id, HttpServletRequest request, HttpServletResponse response){
		DeviceRecipient deviceRecipient = null;
		try {
			deviceRecipient = deviceRecipientService.findById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(deviceRecipient != null){
			String basePath = request.getServletContext().getRealPath("/");
			String templatePath = basePath + File.separator + "templates" + File.separator + "report" + File.separator + "word";
			ReportDeviceRecipientModel rdrm = deviceRecipient.toReportModel();
			ExportUtil.export(response, templatePath, "wz_recipient.vm", "物资领用", "doc", rdrm);
		}
	}
}
